package com.nervenets.general.hibernate;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.nervenets.general.hibernate.type.HibernateJsonStringType;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.SuperBuilder;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.TypeDef;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;

@MappedSuperclass
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
@TypeDef(name = "json", typeClass = HibernateJsonStringType.class)
public abstract class BaseEntity implements Serializable {
    @Version
    @Column(name = "v")
    @ApiModelProperty(value = "数据版本号")
    @JsonIgnore
    @Builder.Default
    protected int version = 0;
    @ApiModelProperty(value = "ID")
    @Id
    @GenericGenerator(name = "snowFlakeIdentifierGenerator", strategy = "com.nervenets.general.utils.SnowFlakeIdentifierGenerator")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "snowFlakeIdentifierGenerator")
    @Builder.Default
    private Long id = null;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof BaseEntity)) return false;
        BaseEntity that = (BaseEntity) o;
        return Objects.equals(getId(), that.getId());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getId());
    }

    @JsonIgnore
    @JSONField(serialize = false)
    public boolean isNew() {
        return null == getId() || 0 == getId();
    }
}
